package com.sywb.chuangyebao.view;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.UserInfo;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.widget.DrawableEditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

public class UserNameActivity extends ActionbarActivity {

    @BindView(R.id.et_name)
    DrawableEditText etName;
    @BindView(R.id.tv_regex)
    TextView tvRegex;

    private String openID;
    private String oldName;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_name_setting;
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        setTitle(R.string.nick_name);
        if (bundle == null) {
            openID = getIntent().getStringExtra("p0");
            oldName = getIntent().getStringExtra("p1");
        } else {
            openID = bundle.getString("p0");
            oldName = bundle.getString("p1");
        }

        if (!TextUtils.isEmpty(oldName)) {
            etName.setText(oldName);
            etName.setSelection(etName.length());
        } else {
            etName.setText(null);
            etName.setHint(R.string.input_nickname);
        }

        setEditTextInhibitInputSpeChat(etName);

        addMenuTextItme(R.string.save, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSetNickname();
            }
        });
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public void setEditTextInhibitInputSpeChat(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) {
                    return "";
                } else {
                    String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                    Pattern pattern = Pattern.compile(speChat);
                    Matcher matcher = pattern.matcher(source.toString());
                    if (matcher.find()) return "";
                    else return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(10)});
    }

    public void doSetNickname() {
        final String name = etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.show(mActivity, R.string.input_nickname);
            return;
        }

        if (name.length() < 2) {
            ToastUtils.show(mActivity, R.string.name_length);
            return;
        }

        if (name.equals(oldName)) {
            exit();
            return;
        }

        HttpUtils.updateUserInfo(null, name, new HttpCallback<String>() {

            @Override
            public void onStart() {
                super.onStart();
                showProgress();
            }

            @Override
            public void onSuccess(String s) {
                UserInfo userInfo = DbManager.getInstance().queryById(openID, UserInfo.class);
                if (userInfo != null && etName != null) {
                    userInfo.nickname = etName.getText().toString().trim();
                    DbManager.getInstance().update(userInfo);
                    // DbManager.getInstance().update(userInfo, new ColumnsValue(new String[]{""}, new String[]{etName.getText().toString()}), ConflictAlgorithm.None)
                }
                // RxBus.get().post(Constants.HTTP_SSO_UPDATEUSERINFO, name);
                exit();
            }

            @Override
            public void onError(String strMsg) {
                super.onError(strMsg);
                ToastUtils.show(mContext, strMsg);
                hideProgress();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgress();
            }
        });

    }

    @Override
    public void initPresenter() {
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("p0", openID);
        outState.putString("p1", oldName);
        super.onSaveInstanceState(outState);
    }

}
